package com.qipay.sp.excutor.deshun;

import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class DeshunNativeExcutor extends AbstractExcutor {

    private final static String API_URL = "api_url";
    @Autowired
    OrderService orderService;
    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("customno", order.getTradeNo());
        apiParams.put("money",
                new BigDecimal(order.getAmount()).divide(new BigDecimal("100"),2,BigDecimal.ROUND_DOWN));
        apiParams.put("sendtime", Long.toString(System.currentTimeMillis()/1000L));
        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object merchant = getVal(spconfig, "merchant");
        Object notifyUrl = getVal(spconfig, "notify_url");
        Object returnUrl = getVal(spconfig, "return_url");
        Object key = getVal(spconfig, "key");

        params.put("merchant",merchant);
        params.put("notifyurl",notifyUrl);
        params.put("backurl",returnUrl);
        params.put("risklevel","3");

        String strSign = "merchant="+params.get("merchant")
                +"&qrtype="+params.get("qrtype")
                +"&customno="+params.get("customno")
                +"&money="+params.get("money")
                +"&sendtime="+params.get("sendtime")
                +"&notifyurl="+params.get("notifyurl")
                +"&backurl="+params.get("backurl")
                +"&risklevel="+params.get("risklevel")
                +key.toString();

        String sign = MD5Util.sign(strSign,"UTF-8").toLowerCase();
        params.put("sign",sign);

        String result = generateAutoSubmitHtml(params,apiUrl.toString());
        Order order = orderService.getByTradeNo(params.get("customno").toString());

        Map<String, Object> resultMap = new HashMap<>();
        order.setState(OrderStateEnum.WAITING.getType());
        orderService.update(order);

        resultMap.put("status", ApiStatusEnum.OK.getCode());
        resultMap.put("pay_info",result);
        return resultMap;
    }

}
